<?php
/**
 * Created by PhpStorm.
 * User: dy
 * Date: 2019/12/31
 * Time: 15:25
 */
namespace app\admin\controller;
use app\admin\model\AdminActionLogModel;
use app\admin\model\AuthGroup;
use app\admin\model\Recycle;
use app\admin\validate\AuthGroupValidate;
use app\common\controller\BackendController;
use think\Exception;
use think\facade\Db;
use think\facade\View;

class Auth extends BackendController
{
    /**
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index(){
        if($this->request->isAjax()){
            $this->model = AuthGroup::instance();
            list($where,$sort,$order,$page,$limit) = $this->model->buildParams($this->request);
            $total = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page,$limit)
                ->order($sort,$order)
                ->select();
            $this->success('查询成功','',['list'=>$list,'total'=>$total]);
        }
        return view();
    }
    protected function treeChange($tree,$checked_ids = []){
        $result = [];
        foreach ($tree as $k=>$item){
            $result[$k]['title'] = $item['name'];
            $result[$k]['id'] = $item['id'];
            $result[$k]['field'] = 'tree_id_'.$item['id'];
            $result[$k]['spread'] = true;
            if(isset($item['child'])){
                $result[$k]['children'] = $this->treeChange($item['child'],$checked_ids);
            }else{
                if(!empty($checked_ids)){
                    if(in_array($item['id'],$checked_ids)){
                        $result[$k]['checked'] = true;
                    }
                }
            }
        }
        return $result;
    }

    public function add(){
        if($this->request->isPost()){
            $data = $this->request->param('post');
            if(!AuthGroupValidate::instance()->scene('add')->check($data)){
                $this->error(AuthGroupValidate::instance()->getError());
            }
            $data['admin_id'] = $this->auth->id;
            $res = AuthGroup::create($data,['name','describe','rules','admin_id']);
            if(!$res){
                $this->error('添加失败');
            }
            AdminActionLogModel::logAdd('添加权限组','权限组名称:'.$data['name']);
            $this->success('添加成功');
        }
        $tree = $this->menu->initMenuTree(false);
        View::assign('tree_list',$this->treeChange($tree));
        return view('edit');
    }
    /**
     * @param null $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit($id = null){
        if($this->request->isPost()){
            $data = $this->request->param('post');
            if(!AuthGroupValidate::instance()->scene('edit')->check($data)){
                $this->error(AuthGroupValidate::instance()->getError());
            }
            $res = AuthGroup::update($data,[],['id','name','describe','rules']);
            if(!$res){
                $this->error('更新失败');
            }
            AdminActionLogModel::logAdd('更新权限组','权限组id:'.$data['id']);
            $this->success('更新成功');
        }
        if(!$id){
            $this->error('id不能为空!');
        }
        $info = AuthGroup::find($id);
        $tree = $this->menu->initMenuTree(false);
        View::assign('info',$info);
        View::assign('tree_list',$this->treeChange($tree,$info->rules_array));
        return view();
    }
    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete(){
        $ids = $this->request->param('ids/a');
        if(empty($ids)){
            $this->error('删除的数据不能为空！');
        }
        $group_list = AuthGroup::select($ids);
        $del_arr = [];
        foreach ($group_list as $group){
            $tmp = [
                'object_id'=>$group['id'],
                'table_name'=>'auth_group',
                'name'=>$group['username'],
                'admin_id'=>$this->auth->id
            ];
            $del_arr[] = $tmp;
        }
        try {
            Db::transaction(function () use ($ids, $del_arr) {
                $res = AuthGroup::destroy($ids);
                if (!$res) {
                    throw new Exception('删除失败！', 401);
                }
                if (!Recycle::instance()->saveAll($del_arr)) {
                    throw new Exception('删除失败！', 402);
                }
            });
            AdminActionLogModel::logAdd('删除权限组','权限组ids:'.json_encode($ids));
            $this->success('删除成功');
        }catch (Exception $e){
            $this->error('删除失败');
        }
    }

    public function status(){
        $ids = $this->request->param('ids/a');
        $status = $this->request->param('status/d');
        if(empty($ids)){
            $this->error('更新的数据不能为空！');
        }
        $res = AuthGroup::update(['status'=>$status],[
            ['id','in',$ids]
        ],['status']);
        if(!$res){
            $this->error('更新失败');
        }
        AdminActionLogModel::logAdd('更新权限组状态','权限组ids:'.json_encode($ids).',status:'.$status);
        $this->success('更新成功');
    }
}